package com.efounder.chat.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.geocoder.RegeocodeRoad;
import com.amap.api.services.geocoder.StreetNumber;
import com.efounder.chat.R;
import com.efounder.chat.adapter.PoiAdapter;
import com.efounder.chat.model.PoiLocation;
import com.efounder.chat.utils.GroupLocationHttpRequest;
import com.efounder.utils.ResStringUtil;
import com.pansoft.library.CloudDiskBasicOperation;
import com.pansoft.library.utils.LogUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.util.TypedValue.COMPLEX_UNIT_SP;


/**
 * zhaojiakun
 * 群聊设置中添加群工作地址
 */


public class ChatGroupAddressActivity extends BaseActivity implements LocationSource, AMapLocationListener, GeocodeSearch.OnGeocodeSearchListener, AdapterView.OnItemClickListener, View.OnClickListener {

    private MapView aMapView;
    private AMap aMap;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;
    private String address;//具体地址
    private String title;//位置
    private ArrayList<PoiLocation> poiList;//周边建筑物列表
    private PoiAdapter adapter;
    private Handler handler = new Handler();

    private double latitude = -1;//选中条目的纬度
    private double longitude = -1;//选中条目的经度
    private int groupId;
    private ListView listView;
    private SmartRefreshLayout sRefreshLayout;
    private LatLng locationLatLng;
    private Marker locationMarker;
    private Marker marker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        去掉标题栏
       // supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_chat_group_address);
        findViewById();

        //在activity执行onCreate时执行aMapView.onCreate(savedInstanceState)，创建地图
        aMapView.onCreate(savedInstanceState);
        //初始化地图控制器对象
        init();
    }

    private void findViewById() {
        //获取地图控件引用
        aMapView = (MapView) findViewById(R.id.map);
        listView = (ListView) findViewById(R.id.lv_poi);
        sRefreshLayout = (SmartRefreshLayout) findViewById(R.id.refreshLayout);
        LinearLayout leftLayout = (LinearLayout) findViewById(R.id.leftbacklayout);
        ImageView backBtn = (ImageView) findViewById(R.id.backButton);
        TextView title = (TextView) findViewById(R.id.fragmenttitle);
        TextView right = (TextView) findViewById(R.id.meeting_date);
        right.setVisibility(View.VISIBLE);
        title.setText(R.string.chat_location);
        right.setText(R.string.common_text_confirm);
        right.setTextSize(COMPLEX_UNIT_SP, 18);
        leftLayout.setVisibility(View.VISIBLE);
        backBtn.setOnClickListener(this);
        right.setOnClickListener(this);
    }

    /**
     * 初始化AMap对象
     */
    private void init() {
        Intent intent = getIntent();
        groupId = intent.getIntExtra("groupid", -1);
        LogUtils.e("groupid" + groupId + "");

        poiList = new ArrayList<>();
        adapter = new PoiAdapter(this, poiList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(this);
        sRefreshLayout.setOnRefreshListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                listView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sRefreshLayout.finishLoadMore();
                    }
                }, 1000);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                listView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        sRefreshLayout.finishRefresh();
                    }
                }, 1000);
            }
        });
        if (aMap == null) {
            aMap = aMapView.getMap();
            setUpMap();
        }
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.drawable.icon_location));// 设置小蓝点的图标
//        myLocationStyle.strokeColor(Color.BLACK);// 设置圆形的边框颜色
        myLocationStyle.radiusFillColor(Color.argb(50, 0, 0, 90));// 设置圆形的填充颜色
//        myLocationStyle.radiusFillColor(Color.parseColor("#77000077"));// 设置圆形的填充颜色
        // myLocationStyle.anchor(int,int)//设置小蓝点的锚点
//        myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        UiSettings uiSettings = aMap.getUiSettings();
        uiSettings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
//        设置地图Logo位置
        uiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_RIGHT);
//        比例尺控件。位于地图右下角
        uiSettings.setScaleControlsEnabled(true);//控制比例尺控件是否显示
//        指南针
        uiSettings.setCompassEnabled(false);
//        缩放按钮
        uiSettings.setZoomControlsEnabled(true);
        uiSettings.setZoomPosition(AMapOptions.ZOOM_POSITION_RIGHT_CENTER);
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
//       触摸监听
        aMap.setOnCameraChangeListener(cameraChangeListener);
//        aMap.setInfoWindowAdapter(infoWindowAdapter);
    }

    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {

        @Override
        public View getInfoWindow(Marker marker) {
//            return null;
            View mContents = getLayoutInflater().inflate(R.layout.custom_info_contents,
                    null);
//            render(marker, mContents);
            return mContents;
        }

        @Override
        public View getInfoContents(Marker marker) {
            View mContents = getLayoutInflater().inflate(R.layout.custom_info_contents,
                    null);
//            render(marker, mContents);
            return mContents;
        }
    };

    /**
     * 自定义infowindow的样式
     */
    public void render(Marker marker, View view) {
        String title = marker.getTitle();
        TextView titleUi = ((TextView) view.findViewById(R.id.title));
        if (title != null) {
            titleUi.setText(title);
        } else {
            titleUi.setText("");
        }
        String snippet = marker.getSnippet();
        TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
        if (snippet != null) {
            snippetUi.setText(snippet);
        } else {
            snippetUi.setText("");
        }
    }

    private boolean isSelectList;//选中条目事件的标识
    /**
     * 滑动事件
     */

    AMap.OnCameraChangeListener cameraChangeListener = new AMap.OnCameraChangeListener() {
        /*设置定位图标位置*/
        @Override

        public void onCameraChange(CameraPosition cameraPosition) {
            LatLng latLng = cameraPosition.target;
            if (locationMarker != null) {
                locationMarker.setPosition(latLng);
            }
            if (null != marker)
                marker.setPosition(latLng);
        }

        /*更新地址列表*/
        @Override

        public void onCameraChangeFinish(CameraPosition position) {
            final LatLng latLng = position.target;
            if (isSelectList) {
                isSelectList = false;
                if (null != marker && !marker.isVisible())
                    marker.setVisible(true);
            } else {
                if (null != marker && marker.isVisible())
                    marker.setVisible(false);
                adapter.index = 0;
                regeocodeSearch(latLng.latitude, latLng.longitude, 3000);
            }
        }
    };

    /**
     * 反地理编码设置
     *
     * @param lat
     * @param lng
     * @param radius
     */
    private void regeocodeSearch(double lat, double lng, float radius) {
        LatLonPoint point = new LatLonPoint(lat, lng);
        GeocodeSearch geocodeSearch = new GeocodeSearch(ChatGroupAddressActivity.this);
        geocodeSearch.setOnGeocodeSearchListener(ChatGroupAddressActivity.this);
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery regeocodeQuery = new RegeocodeQuery(point, radius, GeocodeSearch.AMAP);
        geocodeSearch.getFromLocationAsyn(regeocodeQuery);
    }

    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.backButton) {
//            取消
            setResult(RESULT_OK);
            finish();
        } else if (i == R.id.meeting_date) {
            //确定--返回地址
            Intent data = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("title", title);
            bundle.putString("address", address);
            data.putExtras(bundle);
            setResult(RESULT_OK, data);
//            向后台传经纬度
//            new CloudDiskBasicOperation().cloudDiskGetNextLevelPanFileByFileId();
            GroupLocationHttpRequest request = new GroupLocationHttpRequest();
            request.addGroupPosition("" + groupId, "" + longitude, "" + latitude, address, title, new CloudDiskBasicOperation.ReturnBack() {
                @Override
                public void onReturnBack(String result) throws JSONException {
                    Log.e("addGroupPosition", result + ",currentThread=" + Thread.currentThread().getName());
                    JSONObject object = new JSONObject(result);
                    String result1 = object.getString("result");
                    String info = "";
                    if ("success".equals(result1)) {
                        info = ResStringUtil.getString(R.string.wrchatview_add_group_address_suc);
//                        Toast.makeText(ChatGroupAddressActivity.this, info, Toast.LENGTH_LONG).show();
                    } else {
                        String msg = object.getString("msg");
                        if (null != msg) {
                            if ("the position has exist!".equals(msg)) {
                                info = ResStringUtil.getString(R.string.wrchatview_group_address_already);
//                                Toast.makeText(ChatGroupAddressActivity.this, info, Toast.LENGTH_LONG).show();
                            } else {
                                info = ResStringUtil.getString(R.string.wrchatview_add_group_address_fail);
//                                Toast.makeText(ChatGroupAddressActivity.this, info, Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                    Toast.makeText(ChatGroupAddressActivity.this, info, Toast.LENGTH_LONG).show();
                    finish();
                }
            });

        } else if (i == R.id.ll_chat_group_search) {
            //搜索
            Intent data = new Intent(ChatGroupAddressActivity.this, SearchLocationActivity.class);
            startActivityForResult(data, 1);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            if (1 == requestCode) {
                if (data != null) {
                    Bundle bundle = data.getExtras();
                    double lat = bundle.getDouble("lat");
                    double lng = bundle.getDouble("lng");
//                    更新列表
//                    adapter.index = 0;
                    isSelectList = false;
//                    regeocodeSearch(lat, lng, 3000);
//                    更新位置
                    LatLng latLng = new LatLng(lat, lng);
                    if (null != locationMarker) {
                        locationMarker.setPosition(latLng);
                    }
            /*参数：
            latLng - 可视区域框移动目标点屏幕中心位置的经纬度。
            zoom - 可视区域的缩放级别，高德地图支持3-19 级的缩放级别。*/
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                            latLng, 15));
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行aMapView.onDestroy()，销毁地图
        aMapView.onDestroy();
        //销毁定位对象
        if (null != mlocationClient) {
            mlocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行aMapView.onResume ()，重新绘制加载地图
        aMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行aMapView.onPause ()，暂停地图的绘制
        aMapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行aMapView.onSaveInstanceState (outState)，保存地图当前的状态
        aMapView.onSaveInstanceState(outState);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            //初始化定位  需要传Context类型的参数。推荐用getApplicationConext()方法
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置单次定位 该方法默认为false。
            mLocationOption.setOnceLocation(true);
            //选择定位模式 SDK默认选择使用高精度定位模式。
            // 高精度定位模式:Hight_Accuracy 同时使用网络定位和GPS定位
            //低功耗定位模式：Battery_Saving 不会使用GPS和其他传感器，只会使用网络定位（Wi-Fi和基站定位）
            //仅用设备定位模式：Device_Sensors 不需要连接网络，只使用GPS进行定位，这种模式下不支持室内环境的定位，自 v2.9.0 版本支持返回地址描述信息
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位间隔,单位毫秒,默认为2000ms 最低1000ms
            mLocationOption.setInterval(5000);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新,会增加电量消耗。
            mLocationOption.setWifiActiveScan(true);
//            设置定位请求超时时间，单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(30000);
            //设置是否开启定位缓存机制 缓存机制默认开启true 网络定位结果均会生成本地缓存，
            // 不区分单次定位还是连续定位。GPS定位结果不会被缓存
            mLocationOption.setLocationCacheEnable(true);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();//停止定位后，本地定位服务并不会被销毁
        }
        mlocationClient = null;
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            int errorCode = amapLocation.getErrorCode();
            LogUtils.e("==onLocationChanged.amapLocation====" + amapLocation.toString());
            if (errorCode == 0) {
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                //定位成功回调信息，设置相关消息
                amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                //获取纬度
                latitude = amapLocation.getLatitude();
                //获取经度
                longitude = amapLocation.getLongitude();
                locationLatLng = new LatLng(latitude, longitude);
                amapLocation.getAccuracy();//获取精度信息
                address = amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
                amapLocation.getCountry();//国家信息
                amapLocation.getProvince();//省信息
                amapLocation.getCity();//城市信息
                amapLocation.getDistrict();//城区信息
                amapLocation.getStreet();//街道信息
                amapLocation.getStreetNum();//街道门牌号信息
                amapLocation.getCityCode();//城市编码
                amapLocation.getAdCode();//地区编码
                title = amapLocation.getAoiName();//获取当前定位点的AOI信息
                String name = amapLocation.getPoiName();//获取当前定位点的POI信息
                amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
                amapLocation.getFloor();//获取当前室内定位的楼层
                amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(amapLocation.getTime());
                df.format(date);//定位时间
                String desc = "";
                Bundle locBundle = amapLocation.getExtras();
                if (locBundle != null) {
                    desc = locBundle.getString("desc");
                }
                isSelectList = false;
                addMarker(locationLatLng, desc);
//                locationMarker.showInfoWindow();// 显示信息窗口
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                        locationLatLng, 15));
                //反地理编码搜索
                regeocodeSearch(latitude, longitude, 3000);
            } else {
                String errText = ResStringUtil.getString(R.string.chat_seek_fail) + errorCode + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                title = "";
                address = "";
            }

        }
    }

    /**
     * 定位成功后往地图上添加marker
     *
     * @param latLng
     */
    private void addMarker(LatLng latLng, String desc) {
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_fixed_location));
        MarkerOptions options = new MarkerOptions();
        options.position(latLng);
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.icon_location));
        options.anchor(0.5f,0.5f);//保证小蓝点的中心对应经纬度位置
//        markerOptions.title("[我的位置]");
//        markerOptions.snippet(desc);
//        markerOptions.icon(BitmapDescriptorFactory.defaultMarker());
        marker = aMap.addMarker(options);
        locationMarker = aMap.addMarker(markerOptions);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //当前未选中时
        if (adapter.index != position - 1) {
/*//            设置之前不选中
            if (parent != null) {
                View childAt = parent.getChildAt(index - 1);
                if (null != childAt) {
                    ImageView font_iv = (ImageView) childAt.findViewById(R.id.iv_chat_group_click);
                    if (null != font_iv)
                        font_iv.setVisibility(View.INVISIBLE);
                }
            }

//            设置当前选中
            if (view != null) {
                ImageView iv = (ImageView) view.findViewById(R.id.iv_chat_group_click);
                if (null != iv)
                    iv.setVisibility(View.VISIBLE);
                adapter.index = position - 1;
            }*/
            adapter.index = position - 1;
            isSelectList = true;
            adapter.notifyDataSetChanged();
//            更新定位图标位置
            double latitude = poiList.get(position - 1).getLatitude();
            double longitude = poiList.get(position - 1).getLongitude();
            LatLng latLng = new LatLng(latitude, longitude);
            /*参数：
            latLng - 可视区域框移动目标点屏幕中心位置的经纬度。
            zoom - 可视区域的缩放级别，高德地图支持3-19 级的缩放级别。*/
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    latLng, 15));
        }
//        Map<Integer, Boolean> stateMap = poiList.get(position-1).getStateMap();
//        Boolean isSelected = stateMap.get(position-1);

        title = poiList.get(position - 1).getTitle();
        address = poiList.get(position - 1).getAddress();
        latitude = poiList.get(position - 1).getLatitude();
        longitude = poiList.get(position - 1).getLongitude();
    }

    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int rCode) {
        String preAdd = "";//地址前缀
        if (1000 == rCode) {
            RegeocodeAddress address = regeocodeResult.getRegeocodeAddress();
            StringBuffer stringBuffer = new StringBuffer();
            String area = address.getProvince();//省或直辖市
            String loc = address.getCity();//地级市或直辖市
            String subLoc = address.getDistrict();//区或县或县级市
            String ts = address.getTownship();//乡镇
            String thf = null;//道路
            List<RegeocodeRoad> regeocodeRoads = address.getRoads();//道路列表
            if (regeocodeRoads != null && regeocodeRoads.size() > 0) {
                RegeocodeRoad regeocodeRoad = regeocodeRoads.get(0);
                if (regeocodeRoad != null) {
                    thf = regeocodeRoad.getName();
                }
            }
            String subthf = null;//门牌号
            StreetNumber streetNumber = address.getStreetNumber();
            if (streetNumber != null) {
                subthf = streetNumber.getNumber();
            }
            String fn = address.getBuilding();//标志性建筑,当道路为null时显示
            if (area != null) {
                stringBuffer.append(area);
                preAdd += area;
            }
            if (loc != null && !area.equals(loc)) {
                stringBuffer.append(loc);
                preAdd += loc;
            }
            if (subLoc != null) {
                stringBuffer.append(subLoc);
                preAdd += subLoc;
            }
            if (ts != null)
                stringBuffer.append(ts);
            if (thf != null)
                stringBuffer.append(thf);
            if (subthf != null)
                stringBuffer.append(subthf);
            if ((thf == null && subthf == null) && fn != null && !subLoc.equals(fn))
                stringBuffer.append(fn + ResStringUtil.getString(R.string.chat_nearby));
//            locationMarker.setSnippet(stringBuffer.toString());
            poiList.clear();
            PoiLocation bean = new PoiLocation();
            bean.setTitle(title);
            bean.setAddress(stringBuffer.toString());
            bean.setLatitude(latitude);
            bean.setLongitude(longitude);
            Map<Integer, Boolean> map1 = new HashMap<>();
            map1.put(0, true);
            bean.setStateMap(map1);
            poiList.add(bean);
            String ps = "poi";
            List<PoiItem> pois = address.getPois();
            if (pois != null && pois.size() > 0) {

                for (int i = 0; i < pois.size(); i++) {
                    Map<Integer, Boolean> map = new HashMap<>();
                    map.put(i + 1, false);
                    String title = pois.get(i).getTitle();
                    String adName = pois.get(i).getAdName();
                    String snippet = pois.get(i).getSnippet();
                    LatLonPoint latLonPoint = pois.get(i).getLatLonPoint();
                    double latitude = latLonPoint.getLatitude();
                    double longitude = latLonPoint.getLongitude();
                    PoiLocation pl = new PoiLocation();
                    if (!TextUtils.isEmpty(title))
                        pl.setTitle(title);
                    if (!TextUtils.isEmpty(snippet))
                        pl.setAddress(preAdd + snippet);
                    pl.setLatitude(latitude);
                    pl.setLongitude(longitude);
                    pl.setStateMap(map);
                    poiList.add(pl);
                    ps = ps + ",title=" + title + ",adName=" + adName + ",snippet=" + snippet;
                }
                LogUtils.e("PoiItem" + "pois.size=" + pois.size() + "----" + ps);
                adapter.notifyDataSetChanged();
//                lv.getRefreshableView().setSelection(0);
            }
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }
}
